using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Dune.Business.Managers;

namespace Edge.Common.Web.DataSourceAdapters
{
    /// <summary>
    /// Summary description for FilteredDataSource
    /// </summary>
    public class FilteredDataSource<TDalService, TEntity, TFilter> : BaseDataSource, IFilteringStateProvider
        where TDalService : IFilteredSearch<TEntity, TFilter>
        where TFilter : class, new()
    {

        private IFilterHolder<TFilter> filterHolder;

        public FilteredDataSource(GridView gridView, IFilterHolder<TFilter> filterHolder)
            : base(gridView, false)
        {
            if (filterHolder == null)
                throw new ArgumentException("filterHolder");
            this.filterHolder = filterHolder;
            Init();
        }

        public TFilter Filter
        {
            get
            {
                return filterHolder.Filter;
            }
        }



        protected override BaseDataSourceView CreateDataSourceView()
        {
            return new FilteredDataSourceView<TDalService, TEntity, TFilter>(this, DEFAULT, filterHolder);
        }


        #region IFilteringStateProvider

        [Serializable]
        class FilteringState : IFilteringState
        {
            private object filter;


            public FilteringState(object filter)
            {
                this.filter = filter;
            }


            public override bool Equals(object obj)
            {
                if (this == obj) return true;
                FilteringState filteringState = obj as FilteringState;
                if (filteringState == null) return false;
                return Equals(filter, filteringState.filter);
            }

            public override int GetHashCode()
            {
                return filter != null ? filter.GetHashCode() : 0;
            }
        }

        public IFilteringState GetFilteringState()
        {
            object filter = ((ICloneable)filterHolder.Filter).Clone();
            return new FilteringState(filter);
        }

        #endregion

    }
}
